<?php

/**
 *  后台管理员基类
 */

namespace app\admin\model;

use think\Model;

class BaseModel extends Model
{
    protected $attributes = [];
    protected $enumCallbacks = [];


    /**
     * 获取创建者名称
     * 调用方式->with(['get_creator_name','get_update_name'])
     * @return \think\model\relation\HasOne
     */
    public function getCreatorName()
    {
        return $this->belongsTo(Operator::class, 'creator', 'id')->bind(['creator_value' => 'cname']);
    }

    /**
     * 获取更新者名称
     * 调用方式->with(['get_creator_name','get_update_name'])
     * @return \think\model\relation\HasOne
     */
    public function getUpdateName()
    {
        return $this->belongsTo(Operator::class, 'updater', 'id')->bind(['updater_value' => 'cname']);
    }

    public function getFielUrl($field)
    {
        return $this->hasOne(Images::class, 'id', $field)->bind([$field . '_url' => 'url']);
    }

    /**
     * 获取模型枚举
     * 使用方法:
     * $field(需要获取的字段 默认为ALL全部)
     * enumCallbacks(回调函数  用来处理需要查询数据库的枚举数据)
     * $config(自定义回调函数 与 enumCallbacks可以组合使用)
     * $type(返回数据格式 可用array和label 两种)
     * @param string $field
     * @param $config
     * @param string $type
     * @return array|array[]
     * 2024-11-04 16 31 53
     * author: jiang
     */
    public function getEnum($field, $config = [], $type = 'array')
    {
        $config = array_merge($this->enumCallbacks, $config);

        if ('ALL' === strtoupper($field)) {
            $enums = [];
            foreach ($this->attributes as $key => $values) {
                $enums[$key] = $type == 'label' ? transLabel($values) : $values;
            }
            foreach ($this->enumCallbacks as $key => $item) {
                if (method_exists($this, $item)) {
                    $enums[$key] = $this->$item();
                }
            }
            return $enums;
        } else {
            if (isset($config[$field]) && method_exists($this, $config[$field])) {
                $func = $config[$field];
                return [$field => $this->$func()];
            } else {
                if (!isset($this->attributes[$field])) {
                    return [];
                }
                return [$field => $type == 'label' ? transLabel($this->attributes[$field]) : $this->attributes[$field] ?? []];
            }
        }
    }

    public function transLabel($data)
    {
        $result = [];
        foreach ($data as $key => $value) {
            $result[] = [
                'label' => $value,
                'value' => $key
            ];
        }
        return $result;
    }
    /**
     *  获取枚举字段
     */
    public function getAttributes($field)
    {
        if (isset($this->attributes[$field])) {
            $enum = $this->attributes[$field];
            if (is_array($enum)) {
                return $enum;
            }
        }
    }
}
